use bracket_lib::prelude::*;
use image::*;

pub struct Collectible {
    pub x: i32,     // 小球的x坐标
    pub y: i32,     // 小球的y坐标
    pub collected: bool, // 是否已被收集
    img: DynamicImage, // 新增图片字段
}

impl Collectible {
    pub fn new(x: i32, y: i32) -> Self {
        Collectible {
            x,
            y,
            collected: false,
            img: image::open("assets/collectible.png").unwrap(), // 加载图片
        }
    }

    // 渲染小球（扩展到5x5区域以更好地显示图片）
    pub fn render(&self, ctx: &mut BTerm, player_x: i32) {
        if !self.collected {
            let screen_x = self.x - player_x;
            let (img_width, img_height) = self.img.dimensions();
            
            for dx in 0..5 {
                for dy in 0..5 {
                    let px = screen_x + dx;
                    let py = self.y + dy;
                    if px >= 0 && px < 120 && py >= 0 && py < 80 {
                        // 改进图片采样：将5x5区域映射到图片的对应位置
                        let img_x = (dx as f32 / 5.0 * img_width as f32) as u32;
                        let img_y = (dy as f32 / 5.0 * img_height as f32) as u32;
                        
                        // 确保不超出图片边界
                        let img_x = img_x.min(img_width - 1);
                        let img_y = img_y.min(img_height - 1);
                        
                        let pixel = self.img.get_pixel(img_x, img_y);
                        ctx.set_bg(px, py, (pixel[0], pixel[1], pixel[2]));
                    }
                }
            }
        }
    }

    // 检查是否被玩家收集（玩家与5x5区域有重叠就算吃到）
    pub fn check_collision(&mut self, player: &crate::player::Player) -> bool {
        if !self.collected {
            let player_left = player.x;
            let player_right = player.x + 5; // 6x6区域
            let player_top = player.y;
            let player_bottom = player.y + 5;
            let coll_left = self.x;
            let coll_right = self.x + 4; // 5x5区域
            let coll_top = self.y;
            let coll_bottom = self.y + 4;
            // 判断两个矩形是否有重叠
            let overlap = player_left <= coll_right && player_right >= coll_left &&
                          player_top <= coll_bottom && player_bottom >= coll_top;
            if overlap {
                self.collected = true;
                return true;
            }
        }
        false
    }
} 